#!/usr/bin/env python3
"""Writes the operator's past Tuple calls into the wiki: every stored capture that has no call page yet.

  sidekick-backfill [--env prod staging] [--min-segments 20] [--jobs 4] [--phase pages|digest|all] [--limit N]
                    [--since YYYY-MM-DD] [--model opus] [--dry-run]

Two phases, so the slow part runs in parallel without sessions editing the same files:

1. pages: one `claude -p` per call, oldest first, `--jobs` at a time. Each writes only that call's page (the wiki
   skill's naming and sections) from `$CLI capture show`; this script commits it.
2. digest: the new pages in date order, a batch at a time, one session after another. Each folds its batch into the
   people pages, me.md (how the operator works) and home.md (only what is still open today: newer calls already in
   the wiki win), and commits.

Captures with fewer than --min-segments transcript segments (joins with nothing said) are skipped. The log is
$SIDEKICK_HOME/backfill.log; the list of pages written, for the digest, is $SIDEKICK_HOME/backfill.json.
"""
import argparse
import fcntl
import json
import os
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import date, datetime
from pathlib import Path

sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parent))
import sidekick_context as ctx  # noqa: E402

WIKI = ctx.WIKI.resolve()
STATE = ctx.SIDEKICK / "backfill.json"
LOG = ctx.SIDEKICK / "backfill.log"
BATCH = 8


def log(text):
    line = f"{datetime.now():%H:%M:%S} {text}"
    print(line, flush=True)
    with open(LOG, "a") as f:
        f.write(line + "\n")


def have():
    return {p.stem.split("-")[-1] for p in (WIKI / "calls").rglob("*.md")}


def page_for(short):
    return next(iter(sorted((WIKI / "calls").rglob(f"*-{short}.md"))), None)


def captures(env, min_segments, since):
    code, out, err = ctx.run([ctx.CLIS[env], "capture", "list", "--format", "json"])
    if code:
        log(f"{env}: capture list failed: {err.strip()[:200]}")
        return []
    data = json.loads(out)
    data = data.get("captures", data) if isinstance(data, dict) else data
    done = have()
    return [dict(c, env=env) for c in data
            if c["call_id"][:8] not in done and (c.get("segments") or 0) >= min_segments
            and (not since or c["started_at"][:10] >= since)]


def git(*args):
    return subprocess.run(["git", "-C", str(WIKI), *args], capture_output=True, text=True)


def commit(paths, message):
    with open(WIKI / ".git" / "backfill.lock", "w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        git("add", "--", *map(str, paths))
        r = git("commit", "-q", "-m", message, "--", *map(str, paths))
        return r.returncode == 0


def claude(prompt, task, env, model, turns, timeout):
    home = ctx.SIDEKICK_HOMES[env]
    cmd = ["claude", "-p", "--model", model, *ctx.claude_plugin_args(), "--permission-mode", "auto",
           "--max-turns", str(turns), "--append-system-prompt", prompt, task]
    environ = {**os.environ, "SIDEKICK_HOME": str(home)}
    for key in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"):
        environ.pop(key, None)
    try:
        r = subprocess.run(cmd, cwd=str(ctx.project()), capture_output=True, text=True, stdin=subprocess.DEVNULL,
                           env=environ, timeout=timeout)
        return r.returncode, (r.stdout or r.stderr).strip()
    except (OSError, subprocess.TimeoutExpired) as e:
        return 1, str(e)


def write_page(c, model):
    call, env = c["call_id"], c["env"]
    short = call[:8]
    who = ", ".join(f"{p['full_name']} ({p['id']})" for p in c.get("participants", []))
    prompt = (
        f"This session backfills the operator's wiki with a PAST call. Write ONLY its call page: call {call}, "
        f"{c['started_at']} to {c.get('ended_at')}, Tuple environment {env}, participants {who}. "
        f"SIDEKICK_HOME is {ctx.SIDEKICK_HOMES[env]}; the wiki is {WIKI}. The Tuple CLI is `{ctx.CLIS[env]}`: "
        f"read the transcript with `{ctx.CLIS[env]} capture show {call}`. Follow AGENTS.md in the wiki for the page's "
        "path (calls/<YYYY>/<MM>/<DD>/<HHMMSS>-<short-id>.md, local time), sections and linking: why the call "
        "happened, what happened, decisions, action items with owners. Sidekick was not on this call: Agent "
        "contributions is `**0 sent.**`. Do not create or edit any other file (no people pages, me.md, home.md, "
        "screenshots) and do not commit: a later pass does that. Nobody is watching, so ask no questions."
    )
    started = time.time()
    code, out = claude(prompt, f"Write the wiki call page for past call {call}.", env, model, 40, 20 * 60)
    page = page_for(short)
    if page and commit([page], f"backfill | call {short} ({c['started_at'][:10]}, {env})"):
        log(f"page  {c['started_at'][:10]} {short} {env}: {page.relative_to(WIKI)} in {time.time() - started:.0f} s")
        return str(page.relative_to(WIKI))
    log(f"FAIL  {c['started_at'][:10]} {short} {env}: exit {code}, {out[-300:]!r}")
    return None


def digest(pages, model):
    today = date.today().isoformat()
    for i in range(0, len(pages), BATCH):
        batch = pages[i:i + BATCH]
        prompt = (
            f"This session backfills the operator's wiki ({WIKI}). These call pages were just written from PAST calls, "
            f"oldest first: {', '.join(batch)}. Read them, then fold what they show into the rest of the wiki, as the "
            "wiki skill's \"After a call\" steps 4, 5 and 7 do: each participant's people/ page (role, what they work "
            "on, how they work; named per AGENTS.md with their Tuple user id), me.md's Role & working style (durable "
            "facts about how the operator works, with the call links), and other durable facts where they fit. "
            f"Today is {today} and the wiki already has newer calls: where a page and the wiki disagree, the newer "
            "wins. Add to home.md only what is plausibly still open today, dated. Don't touch Standing constraints or "
            "What lands with me (Sidekick wasn't on these calls). Commit once at the end: "
            f"`git -C {WIKI} commit -qam \"backfill digest | <what changed>\"` after `git add -A`. "
            "Nobody is watching, so ask no questions."
        )
        started = time.time()
        code, out = claude(prompt, "Fold these backfilled call pages into the wiki.", "prod", model, 80, 40 * 60)
        log(f"digest {i // BATCH + 1}/{(len(pages) + BATCH - 1) // BATCH} ({len(batch)} pages): exit {code} in "
            f"{time.time() - started:.0f} s {'' if code == 0 else out[-300:]}")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--env", nargs="+", choices=["prod", "staging", "dev"], default=["prod", "staging"])
    ap.add_argument("--min-segments", type=int, default=20)
    ap.add_argument("--jobs", type=int, default=4)
    ap.add_argument("--phase", choices=["pages", "digest", "all"], default="all")
    ap.add_argument("--limit", type=int)
    ap.add_argument("--since")
    ap.add_argument("--model", default=ctx.agent_model())
    ap.add_argument("--dry-run", action="store_true")
    a = ap.parse_args()

    state = ctx.read_json(STATE) or {"pages": [], "digested": []}
    if a.phase in ("pages", "all"):
        todo = sorted((c for env in a.env for c in captures(env, a.min_segments, a.since)), key=lambda c: c["started_at"])
        todo = todo[: a.limit] if a.limit else todo
        log(f"{len(todo)} calls to write ({', '.join(a.env)}, ≥{a.min_segments} segments), {a.jobs} at a time, {a.model}")
        if a.dry_run:
            for c in todo:
                print(f"  {c['started_at'][:16]} {c['call_id'][:8]} {c['env']:8} {c['segments']:5} segs  "
                      f"{', '.join(p['full_name'] for p in c.get('participants', []))[:90]}")
            return 0
        with ThreadPoolExecutor(a.jobs) as pool:
            written = [p for p in pool.map(lambda c: write_page(c, a.model), todo) if p]
        state["pages"] = sorted(set(state["pages"]) | set(written))
        ctx.write_json(STATE, state)
        log(f"pages done: {len(written)} of {len(todo)} written")
    if a.phase in ("digest", "all") and not a.dry_run:
        pending = [p for p in sorted(state["pages"]) if p not in state["digested"]]
        log(f"digesting {len(pending)} pages, {BATCH} at a time")
        digest(pending, a.model)
        state["digested"] = sorted(set(state["digested"]) | set(pending))
        ctx.write_json(STATE, state)
        log("backfill done")
    return 0


if __name__ == "__main__":
    sys.exit(main())
